package com.zhenyi.fenda.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import com.fenda.common.model.FdAnswer;
import com.fenda.common.model.FdMaster;
import com.fenda.common.model.FdMasterTag;
import com.fenda.common.model.FdNotification;
import com.fenda.common.model.FdQuestion;
import com.fenda.common.model.FdUser;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.weixin.sdk.api.MediaApi;
import com.jfinal.weixin.sdk.api.MediaFile;
import com.utils.AuthUtils;
import com.utils.PathUtils;
import com.utils.image.UploadUtils;
import com.zhenyi.fenda.core.ws.WSServer;
import com.zhenyi.fenda.interceptor.AuthInterceptor;
import com.zhenyi.fenda.interceptor.MasterInterceptor;
import com.zhenyi.fenda.interceptor.WXInterceptor;

import cn.hutool.core.lang.Singleton;
import cn.hutool.json.JSONObject;

/**
 * 大师模块
 * 
 * @author cen
 *
 */
@Before({ AuthInterceptor.class, WXInterceptor.class, MasterInterceptor.class })
public class MasterController extends FDController {

	private WSServer server = Singleton.get(WSServer.class);

	@Override
	public void index() {
		FdUser user = getUser();
		FdMaster master = FdMaster.dao.findById(user.getId());
		setInfoItem(user);
		setAttr("master", master);
		render("/fd/master/userInfo.html");
	}

	public void logout() {
		AuthUtils.logout(this);
		renderSuccess();
	}

	@Clear
	public void debug() {
		Long userId = getParaToLong("userId", 1L);
		AuthUtils.login(String.valueOf(userId), this);
		renderSuccess();
		redirect("/fd/master/");
	}
	
	@Clear(MasterInterceptor.class)
	public void register() {
		FdMaster master = FdMaster.dao.findById(getUser().getId());
		if (master != null) {
			setAttr("registered", 1);
		}
		render("/fd/master/register.html");
	}
	
	@Clear(MasterInterceptor.class)
	public void submitRegister() {
		String json = HttpKit.readData(getRequest());
		JSONObject jsonObject = new JSONObject(json);
		System.out.println(jsonObject);
		String imgServerId = jsonObject.getStr("imgServerId");
		String name = jsonObject.getStr("name");
		String desc = jsonObject.getStr("desc");
		String intro = jsonObject.getStr("intro");
		Integer joinYears = jsonObject.getInt("joinYear");
		String goodAt = jsonObject.getStr("good");
		Integer price = jsonObject.getInt("price");
		Integer oldPrice = jsonObject.getInt("oldPrice");
		
		// 上传封面
		MediaFile coverMediaFile = MediaApi.getMedia(imgServerId);
		String coverFileName = coverMediaFile.getFileName() + ".jpg";
		File coverFile = new File(PathUtils.getFile("upload", coverFileName));
		BufferedInputStream is = coverMediaFile.getFileStream();
		try {
			inputstreamtofile(is, coverFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String coverUrl = UploadUtils.upload(coverFile);

		FdUser user = getUser();
		Long userId = user.getId();

		if (!StrKit.isBlank(goodAt)) {// 修改标签
			Kv cond = Kv.by("userId", userId);
			SqlPara sqlPara = Db.getSqlPara("findMasterTag", cond);
			List<FdMasterTag> list = FdMasterTag.dao.find(sqlPara);
			for (FdMasterTag fdMasterTag : list) {
				fdMasterTag.delete();
			}
			String tagIds[] = goodAt.split(";");
			for (String tagId : tagIds) {
				Long id = Long.parseLong(tagId);
				FdMasterTag fdMasterTag = new FdMasterTag();
				fdMasterTag.setUserId(userId);
				fdMasterTag.setTagId(id);
				fdMasterTag.save();
			}
		}

		FdMaster fdMaster = new FdMaster();
		fdMaster.setUserId(userId);
		if (!StrKit.isBlank(coverUrl)) {// 修改头像
			fdMaster.setLogo(coverUrl);
		}
		if (joinYears != null) {// 修改入职年
			fdMaster.setJoinYears(joinYears);
		}
		if (!StrKit.isBlank(name)) {// 修改名称
			fdMaster.setRealName(name);
		}
		if (!StrKit.isBlank(desc)) {// 修改描述
			fdMaster.setDesc(desc);
		}
		if (!StrKit.isBlank(intro)) {// 修改简介
			fdMaster.setIntro(intro);
		}
		if (price != null) {// 修改价格
			fdMaster.setPrice(price * 100);
		}
		if (oldPrice != null) {
			fdMaster.setOldPrice(oldPrice * 100);
		}
		if (fdMaster.save()) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	private void inputstreamtofile(InputStream ins, File file) throws IOException {
		OutputStream os = new FileOutputStream(file);
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
			os.write(buffer, 0, bytesRead);
		}
		os.close();
		ins.close();
	}

	public void room() {
		FdUser user = getUser();
		Kv cond = Kv.by("nowTime", new Date());
		cond.set("masterId", user.getId());
		SqlPara sqlPara = Db.getSqlPara("FDMasterFindCounsultRooms", cond);
		List<Record> items = Db.find(sqlPara);
		setItems(items);
		render("/fd/master/room.html");
	}

	/**
	 * 需要大师回答的问题
	 */
	public void questions() {
		FdUser user = getUser();
		Long userId = user.getId();
		Kv kv = Kv.create();
		kv.set("masterId", userId);
		SqlPara sqlPara = Db.getSqlPara("FDMasterQuestions", kv);
		List<Record> items = Db.find(sqlPara);
		renderResult(items);
	}

	/**
	 * 还没有标准答案的问题
	 */
	public void allQuestions() {
		SqlPara sqlPara = Db.getSqlPara("FDFindAllQuestions");
		List<Record> items = Db.find(sqlPara);
		renderResult(items);
		setItems(items);
		render("/fd/master/allquestions.html");

	}

	public void answerQuestion() {
		String code = getPara(0);
		setAttr("code", code);
		Long questionId = hashId.decode(code)[0];
		Kv kv = Kv.by("questionId", questionId);
		SqlPara sqlPara = Db.getSqlPara("FdFindQuestion", kv);
		Record record = Db.findFirst(sqlPara);
		print(record);
		setInfoItem(record);
		render("/fd/master/answer.html");
	}

	/**
	 * 回答问题,默认变成问题的标准答案
	 */
	public void answer() {
		String body = getBodyParam();
		JSONObject jsonObject = new JSONObject(body);
		String code = jsonObject.getStr("code");// getBodyPara("code");
		Long questionId = hashId.decode(code)[0];
		String content = jsonObject.getStr("content");
		if (StrKit.isBlank(content)) {
			renderFailure(500, "提交内容为空");
			return;
		}
		FdUser user = getUser();
		Long userId = user.getId();
		FdAnswer answer = new FdAnswer();
		answer.setUserId(userId);
		answer.setContent(content);
		answer.setQuestionId(questionId);
		answer.save();
		Long answerId = answer.getId();
		FdQuestion question = FdQuestion.dao.findById(questionId);
		question.setAnswerId(answerId);
		question.setMasterId(userId);
		question.update();
		FdMaster master = FdMaster.dao.findById(userId);
		master.setAnswerCount(master.getAnswerCount() + 1);
		master.update();

		// 消息提醒
		FdNotification fdNotification = new FdNotification();
		fdNotification.setUserId(question.getUserId());
		fdNotification.setType(NOTIFICACATION_QUESTION);
		fdNotification.setQuestionId(questionId);
		fdNotification.setAddTime(new Date());
		fdNotification.setContent("问题回复提醒");
		fdNotification.save();

		renderSuccess();
	}

	/**
	 * 大师个人信息
	 */
	@Override
	public void info() {
		FdUser user = getUser();
		renderSuccess(user);
	}

	/**
	 * 问题详情
	 */
	public void questionInfo() {
		super.questionInfo();
		setAttr("isMaster", 1);
	}

	/**
	 * 已经回答了的问题
	 */
	public void answeredQuestions() {
		FdUser user = getUser();
		Long userId = user.getId();
		Kv kv = Kv.create();
		kv.set("isAnswered", true);
		kv.set("masterId", userId);
		SqlPara sqlPara = Db.getSqlPara("FDMasterQuestions", kv);
		List<Record> items = Db.find(sqlPara);
		renderResult(items);
	}

	/**
	 * 大师 我的问答
	 */
	public void alreadyMasterQuestions() {
		Integer pageNumber = getParaToInt("pageNumber", 1);
		FdUser user = getUser();
		Long userId = user.getId();
		Kv cond = Kv.by("masterId", userId);
		SqlPara sqlPara = Db.getSqlPara("FDFindMasterQuestions", cond);
		Page<Record> list = Db.paginate(pageNumber, pageSize, sqlPara);
		setAttr("list", list);
		render("/fd/master/masterQuestions.html");
	}

	/**
	 * 大师 我的咨询
	 */
	public void alreadyMasterRooms() {
		Integer pageNumber = getParaToInt("pageNumber", 1);
		FdUser user = getUser();
		Long userId = user.getId();
		Kv cond = Kv.by("masterId", userId);
		SqlPara sqlPara = Db.getSqlPara("FDFindMasterRooms", cond);
		Page<Record> list = Db.paginate(pageNumber, pageSize, sqlPara);
		setAttr("list", list);
		render("/fd/master/roomList.html");
	}

	/**
	 * 大师 我的咨询详情
	 */
	public void alreadyMasterRoomInfo() {
		Integer pageNumber = getParaToInt("pageNumber", 1);
		String code = getPara("code");
		FdUser user = getUser();
		Long roomId = hashId.decode(code)[0];
		// 聊天记录
		Kv cond = Kv.by("roomId", roomId);
		SqlPara sqlPara = Db.getSqlPara("FDFindMessageInRoom", cond);
		Page<Record> list = Db.paginate(pageNumber, pageSize, sqlPara);
		setAttr("list", list.getList());
		setAttr("user", user);
		render("/fd/master/roomInfo.html");
	}

	/**
	 * 去填写修改信息
	 */
	public void goToUpdate() {
		Long userId = getUser().getId();
		FdMaster master = FdMaster.dao.findById(userId);
		if (master == null) {
			renderFailure("您不是老师");
			return;
		}
		
		// find goodAt tag
		StringBuffer goodAtSB = new StringBuffer();
		Kv cond = Kv.by("userId", userId);
		SqlPara sqlPara = Db.getSqlPara("findMasterTag", cond);
		List<FdMasterTag> list = FdMasterTag.dao.find(sqlPara);
		for (FdMasterTag fdMasterTag : list) {
			goodAtSB.append(fdMasterTag.getTagId()).append(";");
		}
		master.put("goodAt", goodAtSB.toString());
		
		setAttr("info", master);
		render("/fd/master/updateMasterInfo.html");
	}

	/**
	 * 更新大师的相关信息
	 */
	public void updateMasterInfo() {

		String json = HttpKit.readData(getRequest());
		JSONObject jsonObject = new JSONObject(json);
		System.out.println(jsonObject);
		String name = jsonObject.getStr("name");
		String desc = jsonObject.getStr("desc");
		String intro = jsonObject.getStr("intro");
		Integer joinYears = jsonObject.getInt("joinYear");
		String goodAt = jsonObject.getStr("good");
		Integer price = jsonObject.getInt("price");
		Integer oldPrice = jsonObject.getInt("oldPrice");
		
		String coverUrl = jsonObject.getStr("url");
		String imgServerId = jsonObject.getStr("imgServerId");
		
		if (imgServerId != null) {
			// 上传封面
			MediaFile coverMediaFile = MediaApi.getMedia(imgServerId);
			String coverFileName = coverMediaFile.getFileName() + ".jpg";
			File coverFile = new File(PathUtils.getFile("upload", coverFileName));
			BufferedInputStream is = coverMediaFile.getFileStream();
			try {
				inputstreamtofile(is, coverFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
			coverUrl = UploadUtils.upload(coverFile);
		}
		
		FdUser user = getUser();
		Long userId = user.getId();

		if (!StrKit.isBlank(goodAt)) {// 修改标签
			Kv cond = Kv.by("userId", userId);
			SqlPara sqlPara = Db.getSqlPara("findMasterTag", cond);
			List<FdMasterTag> list = FdMasterTag.dao.find(sqlPara);
			for (FdMasterTag fdMasterTag : list) {
				fdMasterTag.delete();
			}
			String tagIds[] = goodAt.split(";");
			for (String tagId : tagIds) {
				Long id = Long.parseLong(tagId);
				FdMasterTag fdMasterTag = new FdMasterTag();
				fdMasterTag.setUserId(userId);
				fdMasterTag.setTagId(id);
				fdMasterTag.save();
			}
		}

		FdMaster fdMaster = FdMaster.dao.findById(userId);
		if (coverUrl != null) {// 修改头像
			fdMaster.setLogo(coverUrl);
		}
		if (joinYears != null) {// 修改入职年
			fdMaster.setJoinYears(joinYears);
		}
		if (!StrKit.isBlank(name)) {// 修改名称
			fdMaster.setRealName(name);
		}
		if (!StrKit.isBlank(desc)) {// 修改描述
			fdMaster.setDesc(desc);
		}
		if (!StrKit.isBlank(intro)) {// 修改简介
			fdMaster.setIntro(intro);
		}
		if (price != null) {// 修改价格
			fdMaster.setPrice(price * 100);
		}
		if (oldPrice != null) {
			fdMaster.setOldPrice(oldPrice * 100);
		}
		fdMaster.update();
		renderSuccess();
	}

	public void waitingRoom() {
		FdUser user = getUser();
		SqlPara sqlPara = Db.getSqlPara("FDFindMasterWaitingRoom", user.getId());
		List<Record> items = Db.find(sqlPara);
		renderSuccess(items);
	}

	public void doneRoom() {
	}

	@Clear
	public void send() {
		String uid = getPara("uid");
		server.send("hello", uid);
		renderSuccess();
	}

	@Clear
	public void sta() {
		renderSuccess(server.allChannels.size());
	}
}
